package cn.com.woxitech.dev.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;

import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.common.OrganizationUtils;
import cn.com.woxitech.dev.model.Organization;
import cn.com.woxitech.dev.model.OrganizationManager;
import cn.com.woxitech.dev.model.Room;
import cn.com.woxitech.dev.model.gen.WmOrganization;
import cn.com.woxitech.dev.model.gen.WmOrganizationAdmin;
import cn.com.woxitech.dev.model.gen.WmOrganizationPrivilege;
import cn.com.woxitech.dev.model.gen.WmOrganizationRecommend;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.OrganizationPrivilegeService;
import cn.com.woxitech.dev.service.OrganizationRecommendService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.UserService;

@RestController
@RequestMapping(value="/wjt")
public class OrganizationController{
	private static final Logger logger = Logger.getLogger(RegisterController.class);
	@Autowired 
	UserService userService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	OrganizationPrivilegeService organizationPrivilegeService;
	@Autowired
	RoomService roomService;
	@Autowired
	OrganizationRecommendService organizationRecommendService;
	
	@RequestMapping(value="/org_list",method=RequestMethod.POST)
	public Object getOrgList(@RequestBody String body){
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			List<Organization> organizations = new ArrayList<Organization>();
			String userUuid = jsonNode.get("uuid").asText();
			List<WmOrganizationPrivilege> organizationPrivileges = organizationPrivilegeService.getOrganizationPrivilegeByUserUuid(userUuid);
			if (!organizationPrivileges.isEmpty()) {
				for (WmOrganizationPrivilege organizationPrivilege : organizationPrivileges) {
					String orgUuid = organizationPrivilege.getOrguuid();
					WmOrganization wmOrganization = organizationService.getOrganizationByUuid(orgUuid);
					if (wmOrganization != null) {
						int num = roomService.countRoomByOrguuid(orgUuid);
						Organization organization = OrganizationUtils.createOrganization(num, wmOrganization);
						organizations.add(organization);
					}
				}
				return APIResultFactory.success(organizations);
			}else {
				return APIResultFactory.success(organizations);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
		
	}
	
	@RequestMapping(value="/org_rec_list",method=RequestMethod.GET)
	public Object getRecommendOrgList(){
		List<Organization> organizations = new ArrayList<Organization>();
		List<WmOrganizationRecommend> organizationRecommends = organizationRecommendService.getRecOrgList();
		if (!organizationRecommends.isEmpty()) {
			for (WmOrganizationRecommend organizationRecommend : organizationRecommends) {
				String orgUuid = organizationRecommend.getOrguuid();
				WmOrganization wmOrganization = organizationService.getOrganizationByUuid(orgUuid);
				if (wmOrganization != null) {
					int num = roomService.countRoomByOrguuid(orgUuid);
					Organization organization = OrganizationUtils.createOrganization(num, wmOrganization);
					organizations.add(organization);
				}
			}
			return APIResultFactory.success(organizations);
		}else {
			return APIResultFactory.success(organizations);
		}
		
	}
	
	@RequestMapping(value="/org_create",method=RequestMethod.POST)
	public Object createOrg(@RequestBody String body){
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String unionid = jsonNode.get("unionid").asText();
			String logourl = jsonNode.get("logourl").asText();
			String name = jsonNode.get("name").asText();
			String introduction = jsonNode.get("introduction").asText();
			String type = jsonNode.get("type").asText();
			String title = jsonNode.get("title").asText();
			WmUser user = userService.getUserByUnionId(unionid);
			if (user == null) {
				return APIResultFactory.fail();
			}
			String uuid = user.getUuid();
			List<WmOrganizationPrivilege> organizationPrivileges = organizationPrivilegeService.getOrganizationPrivilegeByUserUuid(uuid);
			
			WmOrganizationAdmin wmOrganizationAdmin = organizationService.getOrganizationAdmin(uuid);
			
			int max = 1;
			
			if(wmOrganizationAdmin != null){
				if(wmOrganizationAdmin.getMaxcount() != null){
					max = wmOrganizationAdmin.getMaxcount().intValue();
				}
			}
			
			if (organizationPrivileges.isEmpty()||organizationPrivileges.size()<max) {
				WmOrganization organization = new WmOrganization();
				organization.setName(name);
				organization.setLogourl(logourl);
				organization.setIntroduction(introduction);
				organization.setType(type);
				organization.setCreator(unionid);
				organization.setTime(new Timestamp(System.currentTimeMillis()));
				organization.setTitle(title);
				String orgUuid = UUID.randomUUID().toString();
				organization.setUuid(orgUuid);
				organizationService.insertOrganization(organization);
				WmOrganizationPrivilege organizationPrivilege = new WmOrganizationPrivilege();
				organizationPrivilege.setOrguuid(orgUuid);
				organizationPrivilege.setPrivilege("1");
				organizationPrivilege.setUseruuid(uuid);
				organizationPrivilegeService.insertOrganizationPrivilege(organizationPrivilege);
				return APIResultFactory.success(orgUuid);
			}else {
				return APIResultFactory.fail("exceed");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		} 
		
	}
	
	@RequestMapping(value="/org_update",method=RequestMethod.POST)
	public Object updateOrg(@RequestBody String body){
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			String orgUuid = jsonNode.get("orguuid").asText();
			String unionid = null;
			String logourl = null;
			String name = null;
			String introduction = null;
			String type = null;
			String title = null;
			if (jsonNode.has("unionid")) {
				unionid = jsonNode.get("unionid").asText();
			}
			if (jsonNode.has("logourl")) {
				logourl = jsonNode.get("logourl").asText();	
			}
			if (jsonNode.has("name")) {
				name = jsonNode.get("name").asText();
			}
			if (jsonNode.has("introduction")) {
				introduction = jsonNode.get("introduction").asText();
			}
			if (jsonNode.has("type")) {
				type = jsonNode.get("type").asText();
			}
			if (jsonNode.has("title")) {
				title = jsonNode.get("title").asText();
			}
			
			WmOrganization organization = organizationService.getOrganizationByUuid(orgUuid);
			if (!StringUtils.isEmpty(unionid)) {
				organization.setCreator(unionid);
			}
			if (!StringUtils.isEmpty(logourl)) {
				organization.setLogourl(logourl);
			}
			if (!StringUtils.isEmpty(name)) {
				organization.setName(name);
			}
			if (!StringUtils.isEmpty(introduction)) {
				organization.setIntroduction(introduction);
			}
			if (!StringUtils.isEmpty(type)) {
				organization.setType(type);
			}
			if (!StringUtils.isEmpty(title)) {
				organization.setTitle(title);
			}
			organizationService.updateByPrimaryKey(organization);
			return APIResultFactory.success();
		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/org_details",method=RequestMethod.POST)
	public Object getOrgDetails(@RequestBody String body){
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String orgUuid = jsonNode.get("orguuid").asText();
			String unionid = jsonNode.get("unionid").asText();
			List<WmRoom> rooms = roomService.getRoomsByOrgUuid(orgUuid);
			int attends = 0;
			List<Room> list = new ArrayList<Room>();
			for (WmRoom wmRoom : rooms) {
				Room room = new Room();
				room.setDes(wmRoom.getDes());
				room.setName(wmRoom.getName());
				room.setRoomtype(wmRoom.getRoomType());
				room.setThumburl(wmRoom.getThumburl());
				room.setTime(wmRoom.getTime());
				room.setType(wmRoom.getType());
				room.setUuid(wmRoom.getUuid());
				attends += wmRoom.getAttendeecount();
				list.add(room);
			}
			
			WmOrganization organization = organizationService.getOrganizationByUuid(orgUuid);
			OrganizationManager organizationManager = new OrganizationManager();
			organizationManager.setAttends(attends);
			organizationManager.setName(organization.getName());
			organizationManager.setRooms(list);
			organizationManager.setUnionid(unionid);
			organizationManager.setUuid(orgUuid);
			organizationManager.setLogourl(organization.getLogourl());
			return APIResultFactory.success(organizationManager);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		} 
		
	}
}
